package middleware

import (
	"duoke/model"
	"duoke/service"
	"duoke/utils/gconv"
	"duoke/utils/gmd5"
	"duoke/utils/orm"
	"duoke/utils/request"
	"duoke/utils/response"
	"github.com/gin-gonic/gin"
)

func Screenbord() gin.HandlerFunc {
	return func(c *gin.Context) {
		req := request.JsonMap(c)
		if req["goods_id"] == nil || req["goods_id"] == "" {
			response.Error(c, "商品ID缺失", nil)
			c.Abort()
			return
		}
		goods := new(model.ReqGoods)
		has, err := orm.Db.ID(gconv.Int(req["goods_id"])).Get(goods)
		if err != nil {
			response.Error(c, err.Error(), nil)
			c.Abort()
			return
		}
		if !has {
			response.Error(c, "商品不存在", nil)
			c.Abort()
			return
		}
		goods.Sales = service.Goods.Sales(goods.Id)
		goods.Income = service.Goods.Income(goods.Id)
		c.Set("goods", *goods)
		if req["token"] == nil || req["token"] == "" {
			response.Error(c, "token缺失", nil)
			c.Abort()
			return
		}
		if gmd5.MustEncrypt(gconv.String(req["goods_id"])+goods.ScreenboardPassword) != req["token"] {
			response.Error(c, "链接已失效，请重新从后台获取新链接", nil)
			c.Abort()
			return
		}
		c.Set("account", service.AccountStruct{Id: goods.Acid})
		c.Next()
	}
}
